package com.bwstudio.common.autoidempotent.service;

import com.bwstudio.common.autoidempotent.config.AutoIdempotentProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @author buwei
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RedisServiceImpl implements RedisService {

    private final RedisTemplate<String,String> redisTemplate;

    /**
     *  写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    @Override
    public boolean set(String key, String value) {
        boolean result = false;
        try {
            /*ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(key, value);*/
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间
     * @param key
     * @param value
     * @param expireTime  过期时间，单位：ms
     * @return
     */
    @Override
    public boolean setEx(String key, String value, Long expireTime) {
        boolean result = false;
        try {
            /*ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.MILLISECONDS);*/

            redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.MILLISECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    @Override
    public boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     * @param key
     * @return
     */
    @Override
    public String get(String key) {
        String result = null;
        result = redisTemplate.opsForValue().get(key);
        return result;
    }

    /**
     * 删除对应的value
     * @param key
     */
    @Override
    public boolean remove(String key) {
        if (exists(key)) {
            Boolean delete = redisTemplate.delete(key);
            return delete;
        }
        return false;
    }
}
